import pytest
from numpy.f2py.auxfuncs import options
from selenium import webdriver
from other.selenium_demo import driver
from util_tools.logs_util.recordlog import logs
from config.setting import browser_type, WAIT_TIME, headless
from pageObject.login_page.login_page import LoginPage
import allure
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

@pytest.fixture(autouse=True)
def log_outputs():
    logs.info('------测试用例开始执行testcase------')
    yield
    logs.info('------测试用例执行完毕testcase------')

def init_driver():
    browser_mapping = {
        'Chrome': webdriver.Chrome,
        'Edge': webdriver.Edge,
        'Firefox': webdriver.Firefox
    }
    options = None
    if browser_type.capitalize() == 'Chrome':
        options = ChromeOptions()
        options.add_argument('--headless')
    elif browser_type.capitalize() == 'Edge':
        options = EdgeOptions()
        options.add_argument('--headless')
    elif browser_type.capitalize() == 'Firefox':
        options = FirefoxOptions()
        options.add_argument('--headless')
    if browser_type.capitalize() in browser_mapping:
        return browser_mapping.get(browser_type.capitalize())(options=options if headless else None)

@pytest.fixture(scope='class')
def get_driver():
    driver = init_driver()
    driver.implicitly_wait(WAIT_TIME)
    driver.maximize_window()
    yield driver
    driver.quit()

@pytest.fixture(scope='class')
def login_driver(get_driver):
    driver = get_driver
    login_page = LoginPage(driver)
    login_page.login('admin123', '123456')
    return driver

@pytest.fixture()
def not_login_driver():
    global driver
    driver = init_driver()
    driver.implicitly_wait(WAIT_TIME)
    driver.maximize_window()
    yield driver
    driver.quit()

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport():
    coucome = yield
    result = coucome.get_result()
    if result.when == 'call':
        xfail = hasattr(result, 'wasxfail')
        if (result.skipped and xfail) or (result.failed and not xfail):
            with allure.step('测试用例失败截图'):
                allure.attach(driver.get_screenshot_as_png(), '失败截图', attachment_type=allure.attachment_type.PNG)